package com.kaochong.xcx.utils;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * RestTemplate工具类
 * @author han
 * @date 2018-03-16 15:39
 */
public class RestTemplateUtils {
	
	private static class SingletonRestTemplate {
		/**
		 * 单例对象实例
		 */
		static final RestTemplate INSTANCE = new RestTemplate();
	}
	
	private RestTemplateUtils() {}
	
	/**
	 * 单例实例
	 */
	public static RestTemplate getInstance() {
		return SingletonRestTemplate.INSTANCE;
	}
	
	public static String get(String url){
		return get(url, null);
	}
	
	public static String get(String url, Map<String, Object> paramMap){
		if(paramMap != null && !paramMap.isEmpty()) {
			StringBuffer param = new StringBuffer();
			int i = 0;
			for (String key : paramMap.keySet()) {
				if (i == 0) {
					param.append("?");
				} else {
					param.append("&");
				}
				param.append(key).append("=").append(paramMap.get(key));
				i++;
			}
			url += param;
		}
		System.out.println(url);
		String response = getInstance().getForObject(url, String.class);
		return response;
	}
	
	/**
	 * 发送post请求
	 * @param url 请求URL地址
	 * @param data json数据
	 */
	public static String post(String url, String data) {
		HttpHeaders headers = new HttpHeaders();
		headers.add("Accept", "application/json");
		headers.add("Accpet-Encoding", "gzip");
		headers.add("Content-Encoding", "UTF-8");
		headers.add("Content-Type", "application/json; charset=UTF-8");
		
		HttpEntity<String> formEntity = new HttpEntity<>(data, headers);
		return RestTemplateUtils.getInstance().postForObject(url, formEntity, String.class);
	}
	
	
	/**
	 * post提交对象
	 */
//	public String post(String url, String data) {
//		return RestTemplateUtils.getInstance().postForObject(url, null,
//				String.class, data);
//	}
}
